/**
 * 分级管理Model页面
 */
import React, { Component } from 'react';
import { Modal, Button, Form, Input, message } from 'antd';
import { saveOrEditClassifies, checkClassifiName } from '../../Server/SystemManger';
import * as Utils from '../../common/utils';
import * as Const from '../../common/const'
import qs from 'qs';

const FormItem = Form.Item;
let sysCompany = {};

class ClassifiesModal extends Component{
    constructor(props) {
        super(props);
        const user = JSON.parse(localStorage.getItem('user'));
        sysCompany = user?user.sysCompany:{};
    }

    //保存方法
    handleSubmit = (e) => {
        e.preventDefault();
        const { form, row, current, getInvalidateFunc, size, nameText } = this.props
        form.validateFieldsAndScroll((err, values) => {
            if(!err){
                let updateState = row.id!=undefined
                values.id = updateState?row.id:null;
                values.name = values.name.replace(/\s*/g,"");
                const param = values;
                const _param = qs.stringify(param);
                saveOrEditClassifies(_param).then(res => {
                    if(res && res.code == Const.REQUEST_SUCCESS){
                        this.props.showNewBranch({} , false);
                        this.props.getTableData({page: current?current-1:0, size: size(), name: nameText});
                        getInvalidateFunc()
                        message.success(updateState?'修改成功！':'新增成功！', 1);
                    }else{
                        res && res.code !== Const.REQUEST_UNAUTHORIZED && message.error(res.msg, 2);
                    }
                });
            }
        });
    }

    //校验起始ip
    checkStartIP = (rule, value, callback) =>{
        if(value==''||value==undefined){
            callback('请输入起始IP地址！');
            return ;
        }else if(!Utils.checkIP(value)){
            callback('请输入正确地IP地址！');
            return ;
        }else if(this.props.form.getFieldValue("endIp") && Utils.compareIP(this.props.form.getFieldValue("startIp"),this.props.form.getFieldValue("endIp")) == 1){
            callback('起始IP不能大于结束IP');
            return ;
        }
        callback();
        if(this.props.form.getFieldValue('endIp') && this.props.form.getFieldError('endIp')){
            this.props.form.validateFields(['endIp'],{ force: true });
        }
    }

    //校验结束ip
    checkEndIP = (rule, value, callback) =>{
        if(value==''||value==undefined){
            callback('请输入结束IP地址！');
            return ;
        }else if(!Utils.checkIP(value)){
            callback('请输入正确地IP地址！');
            return ;
        }else if(this.props.form.getFieldValue("startIp") && Utils.compareIP(this.props.form.getFieldValue("startIp"),this.props.form.getFieldValue("endIp"))==1){
            callback('结束IP不能小于起始IP');
            return ;
        }
        callback();
        if(this.props.form.getFieldValue('startIp') && this.props.form.getFieldError('startIp')){
            this.props.form.validateFields(['startIp'],{ force: true });
        }
    }

    //校验分部名称
    validatePartName = (rule, value, callback) => {
        if (value == '' || value == undefined) {
            callback("请输入分部名称");
            return;
        }
        if(value && value.length){
            const params = {name:value};
            this.props.id && (params.id = this.props.id);
            checkClassifiName(qs.stringify(params)).then(res => {
                if(res && Const.REQUEST_SUCCESS == res.code && !res.data){
                    callback(Const.VALIDATOR_FAIL_TIP);
                }else{
                    callback();//注意:回调函数必须调用
                }
            });
        }else{
            callback();
        }
    }

    render(){
        const { showNewBranch, row } = this.props;
        const { getFieldDecorator } = this.props.form;
        const formItemLayout = {
            labelCol: {
              xs: { span: 24 },
              sm: { span: 8 },
            },
            wrapperCol: {
              xs: { span: 24 },
              sm: { span: 12 },
            },
        };

        return(
            <Modal 
                visible={true}
                width="50%"
                title={row.id?"修改分级":"新增分级"}
                footer={null}
                maskClosable={false}
                onCancel={()=>showNewBranch({} , false)}
            >
                <Form onSubmit={this.handleSubmit} >
                    <FormItem
                        {...formItemLayout}
                        label="分部名称"
                        >
                        {getFieldDecorator('name',{
                            rules: [{
                                required: true, 
                                validator: this.validatePartName
                            }],
                            initialValue: row.name || '',
                        })(
                            <Input maxLength={255}/>
                        )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="起始IP"
                        >
                        {getFieldDecorator('startIp', {
                            rules: [{
                                required: true, 
                                validator: this.checkStartIP 
                            }],
                            initialValue: row.startIp || '',
                        })(
                            <Input maxLength={20}/>
                        )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="结束IP"
                        >
                        {getFieldDecorator('endIp', {
                            rules: [{
                                required: true, 
                                validator: this.checkEndIP 
                            }],
                            initialValue: row.endIp || '',
                        })(
                            <Input maxLength={20}/>
                        )}
                    </FormItem>
                    <FormItem style={{textAlign:'center'}}>
                        <Button type="primary" htmlType="submit"  className="conform-button">保存</Button>
                        <Button type="primary" onClick={()=>showNewBranch({} , false)}>返回</Button>
                    </FormItem>
                </Form>

            </Modal>
        )
    }
}

export default Form.create()(ClassifiesModal)